<template>
  <div id="bi-container" ref="biContainer">
    <slot />
  </div>
</template>

<script setup>
import { nextTick } from 'vue'

const { proxy } = getCurrentInstance()

const props = defineProps({
  options: {
    type: Object,
    default: () => ({
      width: 1920,
      height: 1080
    })
  }
})

const width = ref(0)
const height = ref(0)
const originalWidth = window.screen.width
const originalHeight = window.screen.height
let resizeTimeout = null

const biContainer = ref(null)

const initSize = async () => {
  await nextTick()
  if (props.options.width && props.options.height) {
    width.value = props.options.width
    height.value = props.options.height
  } else {
    width.value = biContainer.value.clientWidth
    height.value = biContainer.value.clientHeight
  }
}

const updateSize = () => {
  if (biContainer.value) {
    biContainer.value.style.width = `${width.value}px`
    biContainer.value.style.height = `${height.value}px`
  }
}

// Update scale
const updateScale = () => {
  const bodyRect = document.body.getBoundingClientRect()
  const currentWidth = bodyRect.width
  const currentHeight = bodyRect.height
  const realWidth = width.value || originalWidth
  const realHeight = height.value || originalHeight
  const widthScale = currentWidth / realWidth
  const heightScale = currentHeight / realHeight

  if (biContainer.value) {
    biContainer.value.style.transform = `scale(${widthScale}, ${heightScale})`
  }
}

// Handle resize event
const onResize = async () => {
  await initSize()
  updateScale()
}

// Throttled resize handler
const onResizeThrottled = () => {
  if (!resizeTimeout) {
    resizeTimeout = setTimeout(() => {
      resizeTimeout = null
      onResize()
    }, 300) // Adjust the throttling interval as needed
  }
}

onMounted(async () => {
  await initSize()
  updateSize()
  updateScale()
  window.addEventListener('resize', onResizeThrottled)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', onResizeThrottled)
})
</script>
<style scoped lang='scss'>
#bi-container {
  position: fixed;
  top: 0;
  overflow: hidden;
  transform-origin: left top;
  z-index: 1001;
  pointer-events: none;
  height: 100%;
  width: 100%;
}
</style>